﻿using System;
using System.Text;

namespace SimpleTerminal.Common
{
    class BytesToUCS
    {
        private byte[] Incomplete = new byte[6];
        private int bytesCount = 0;


        public void Test()
        {

            byte[] bytes2 = { (byte)'\xe5', (byte)'\xa5', (byte)'\xbd' };

            char[] test = { '好' };
            int c = Encoding.UTF8.GetCharCount(bytes2);
            char[] bytes = Encoding.UTF8.GetChars(bytes2);

            Console.WriteLine(new string(bytes) + " " + c);

            // foreach(byte b in bytes)
            ////{
            //    Console.WriteLine("{0,4:X4}",b);
            //}
        }

        /*
         public char[] Utf8ToUcs(byte[] bytes)
         {
             int len = bytes.Length;
             int pos;
             char head;
             if (bytesCount > 0)
             {
                 int ucssize = 0;
                 while ((Incomplete[0] & 0x80) == 0x80)
                     ucssize++;
                 Array.Copy(bytes,0,Incomplete,bytesCount,ucssize-bytesCount);
                 bytesCount = 0;
                 Encoding.UTF8.GetChars(bytes,0,ucssize);
                 //head = 
             }

             for (pos = len - 1; pos >= 0; pos--)
             {

                 //是ASCII字符
                 if ((bytes[pos] & 0x80) == 0x00)
                 {
                     bytesCount = 0;
                     break;
                 }
                 //讲此为与c0相与(1100 0000) 如果结果是(10xx xxxx)
                 else if ((bytes[pos] & 0xc0) == 0x80)
                 {
                     bytesCount++;
                     continue;
                 }
                 else
                 {

                      // 判断UTF8是否完整，例如，从后向前已经读取到3个10xx xxxx格式的数据
                      // 那么当前格式则应该为 1111 0xxx ，否则此UTF8则可能为截断字符
                      // 之所以开头是四个1是因为要包含先导字节自身

                     if ((bytes[pos] & (0xff << (8 - bytesCount - 2))) == (0xff << (8 - bytesCount - 1)))
                     {
                         bytesCount = 0;
                         break;
                     }
                     else
                     {
                         bytesCount++;
                         //UTF8可能被截断
                         Array.Copy(bytes, pos, Incomplete, 0, bytesCount);
                     }
                 }
             }
         }
        */
    }
}
